﻿<%@ WebHandler Language="C#" Class="LoginHandler" %>

using System;
using System.Web;
using Newtonsoft.Json.Linq;
using System.Web.Security;
using System.Text;
using Web.Library.DomainObject.SQLServer;
using Web.Library.Facade.SQLServer;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Configuration;
using Web.Support;


public class LoginHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    
    public void ProcessRequest (HttpContext context) {
        System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

        string jsonString = string.Empty;
        jsonString = context.Server.UrlDecode(sr.ReadToEnd());
        JObject jO = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

        sr.Close();
        sr.Dispose();

        string username = (string)jO["UserCode"];
        string password = (string)jO["Password"];


        bool isPersistent = (string)jO["Password"] == "true" ? true : false;
        string message = "Kode atau sandi anda salah!";

        //recUser user = null;
        SysUser user = null;
        string url = FormsAuthentication.DefaultUrl;
        bool isValid = false;

        try
        {
            SysUserFacade Facade = new SysUserFacade(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
            isValid = Facade.ValidateUser(username, password, out user);
            //if (isValid == true) // cek apakah usrname dan pass valid
            //{
            //    if (user.IsActive == false)
            //    {
            //        isValid = false;
            //        message = "User yang digunakan tidak aktif";
            //    }
            //    else if (user.IsForgotPass == true)
            //    {
            //        //recParameterRepo recParameterDal = new recParameterRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
            //        //recParameter Password = recParameterDal.GetById("PWD");
            //        //string HasPassword = Helper.CreatePasswordHash(SIPO.Web..GeneratePassword(5,0);
            //        //if (password.ToUpper() == HasPassword)
            //        //{
            //        url += "?forgotpassword=true";
            //        //}
            //        user.IsForgotPass = false;
            //        recUserRepo recUserDal = new recUserRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
            //        recUserDal.Update(user);
            //    }
            //}



        }
        catch (Exception ex)
        {
            message = ex.Message;

            //result = "{success: false, message: 'Error found on page! " + ConfigurationManager.AppSettings["ErrorHelpText"].ToString() + "'}";
            //log.Debug("Process() on GroupAuthorizationHandler.ashx.cs: " + ex.Message.ToString());

            //Logger.Error("LogIn on LoginHandler.ashx " + ex.Message);
            Logger.Debug("LogIn () on LoginHandler.ashx", ex); 
        }
        finally
        {

            if (isValid)
            {
                string userData = string.Empty;
                ////bool isIndividual = false;

                //UserData format -> UserID | GroupID |  GroupAppID
                userData = user.UserID.ToString() + "|" + user.GroupID.ToString() + "|" + user.GroupAppID.ToString() +"|" + user.UserCode;// +"|" + user.Position.LocationID + "|" + user.IsLocation + "|" + user.IsDepartment + "|" + user.IsLocationID + "|" + user.IsDepartmentID;

                // Create a new ticket for user that has been authenticated.                    
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                    user.Name,
                    DateTime.Now,
                    DateTime.Now.Date.AddDays(1),
                    isPersistent,
                    userData,
                    FormsAuthentication.FormsCookiePath);

                // Create the cookie.
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                cookie.Value = FormsAuthentication.Encrypt(ticket);
                cookie.Expires = ticket.Expiration;
                context.Response.Cookies.Add(cookie);
                context.Session["UserLoggedIn"] = user.UserCode;
            }
        }

        string app = "http://" + context.Request.Url.Host + ":" + context.Request.Url.Port.ToString();

        StringBuilder sb = new StringBuilder();
        sb.Append("{");
        sb.AppendFormat("  {0}DefaultUrl{0}:{0}{1}{0}", "\"", app + url);
        sb.Append(",");
        sb.AppendFormat("  {0}IsValid{0}:{0}{1}{0}", "\"", isValid);
        sb.Append(",");
        sb.AppendFormat("  {0}Message{0}:{0}{1}{0}", "\"", message);
        sb.Append("}");

        context.Response.Write(sb.ToString());
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}